package com.itheima.service.impl;

import com.itheima.mapper.CityMapper;
import com.itheima.pojo.City;
import com.itheima.service.CityService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@RequiredArgsConstructor
@Service
public class CityServiceImpl implements CityService {
    
    private final CityMapper cityMapper;

    @Override
    public List<City> listAll() {
        // 查询所有城市
        List<City> list = cityMapper.list();
        
        // 找到所有顶级城市（省份）
        List<City> provinces = list.stream().filter(c -> c.getParentId() == 0).collect(Collectors.toList());
        
        // 找到所有非顶级城市
        List<City> children = list.stream().filter(c -> c.getParentId() > 0).collect(Collectors.toList());
        
        // 递归查找子城市
        provinces.forEach(province -> findChildren(province, children));
        
        return provinces;
    }
    
    /***
     * 递归查找子城市
     */
    public void findChildren(City city, List<City> children) {
        // 循环所有子城市，判断查找当前城市的子城市
        List<City> list = children.stream()
                .filter(c -> Objects.equals(c.getParentId(), city.getId()))
                .collect(Collectors.toList());
        
        // 如果没有子城市，则结束，有就继续查找（递归查找）
        list.forEach(c -> findChildren(c, children));
        
        // 将查找的结果赋值给当前城市的子城市属性children
        city.setChildren(list);
    }
}